import time
from car_base.constant import *
from car_base.uart_init import UartConfig
from car_base.wifi_init import WifiConfig

class CarDrive():
    def __init__(self, cline="wifi", with_flag=True):
        if cline == "uart":
            cline = UartConfig()
        elif cline == "wifi":
            cline = WifiConfig()
        self.with_flag = with_flag
        self.client = cline
        self.speed = 80
        self.car_dev = MAIN_CAR

    def _withFlag(self, value):
        while self.with_flag:
            time.sleep(0.2)
            data_msg = self.client.datRead(flag=False)
            print("wifi_msg:", data_msg.hex())
            if(data_msg[2] == value):
                break

    """
    小车基本运动控制：停止、前进、后退、左转、右转、循迹
    """
    def stop(self):
        self.client.datSeed(self.car_dev, 0x01, 0, 0, 0)
        self._withFlag(0x00)

    def go(self, speed=80, mp=400):
        if self.with_flag:
            self.stop()
        self.client.datSeed(self.car_dev, 0x02, speed, mp % 256, mp >> 8)
        self._withFlag(0x03)

    def dow(self, speed=80, mp=400):
        if self.with_flag:
            self.stop()
        self.client.datSeed(self.car_dev, 0x03, speed, mp % 256, mp >> 8)
        self._withFlag(0x03)

    def left(self, speed=80):
        if self.with_flag:
            self.stop()
        self.client.datSeed(self.car_dev, 0x04, speed, 0, 0)
        self._withFlag(0x02)

    def right(self, speed=80):
        if self.with_flag:
            self.stop()
        self.client.datSeed(self.car_dev, 0x05, speed, 0, 0)
        self._withFlag(0x02)

    def xj(self, speed=80):
        if self.with_flag:
            self.stop()
        self.client.datSeed(self.car_dev, 0x06, speed, 0, 0)
        self._withFlag(0x01)

    # 沙盘标志物控制
    # 道闸开启或关闭
    def gate_con(self, value):
        self.client.datSeed(ROAD_GATE, 0x01, value, 0, 0)
        time.sleep(1)

    # 道闸显示车牌信息
    def gate_plate(self, plt=""):
        if len(plt) != 6:
            print("--plate_len_err!!")
        else:
            plate = list(map(ord, plt))
            a, b, c, d, e, f = plate
            self.client.datSeed(ROAD_GATE, 0x10, a, b, c)
            time.sleep(0.3)
            self.client.datSeed(ROAD_GATE, 0x11, d, e, f)
            time.sleep(2)

    # TFT显示标志物
    def tft_dis(self, value):
        self.client.datSeed(TFT_SHOW_A, 0x10, value, 0, 0)
        time.sleep(0.3)

